import {
    Apply
} from './apply.model'
import {
    Member
} from './../member/member.model'
import Toast from '@vant/weapp/toast/toast'
import Dialog from '@vant/weapp/dialog/dialog'
const apply = new Apply()
const member = new Member()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isAuth: false, // 是否授权
        // 检车站信息
        station: {
            id: '',
            station_name: '检车站',
            station_address: '哈尔滨市红军街1号',
            goods_id: '',
            goods_name: '安检+尾气',
            goods_price: 0,
            vehicle_id: '',
            vehicle_name: '小型车',
            subscribe_id: '',
            subscribe_date: '2000-01-01 08:00'
        },
        licenseList: [], // 行驶证名称集合
        licenseIndex: [], // 行驶证ID集合
        couponList: [], // 优惠券名称集合
        couponIndex: [], // 优惠券ID集合
        currentDate: 0, // 当前日期
        driving_license_id: '', // 行驶证ID
        currentLicenseNumber: '', // 当前选择的行驶证名称
        coupon_id: '', // 优惠券ID
        currentCouponNumber: '', // 当前选择的优惠券名称
        showDatePopup: false, // 是否显示日期面板
        showLicensePopup: false, // 是否显示行驶证面板
        showCouponPopup: false, // 是否显示优惠券面板
        minDate: new Date().getTime(), // 可选最早日期
        // 格式化日期选择器文字
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            }
            if (type === 'month') {
                return `${value}月`
            }
            return value
        },
    },

    /**
     * 生命周期函数--监听页面加载
     * @param {*} options
     */
    onLoad(options) {
        let that = this
        // 是否授权
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    that.setData({
                        isAuth: true
                    })
                    that._loadData()
                }
            }
        })
        that.setData({
            station: options,
        })
    },

    /**
     * 获取所有数据
     */
    _loadData() {
        let that = this
        that.getLicenseData()
    },

    /**
     * 获取行驶证列表
     */
    getLicenseData() {
        let that = this,
            licenseList = [],
            licenseIndex = []
        apply.getLicenseData().then((res) => {
            for (let key in res.data) {
                if (res.data.hasOwnProperty(key)) {
                    let element = res.data[key]
                    licenseList.push(element['license_number'])
                    licenseIndex.push(element['id'])
                }
            }
            licenseList.push('+新增行驶证')
            licenseIndex.push('-1')
            that.setData({
                licenseList: licenseList,
                licenseIndex: licenseIndex
            })
        })
    },

    /**
     * 选择预约日期
     */
    onTapDate() {
        this.setData({
            showDatePopup: true
        })
    },

    /**
     * 确认日期选择
     * @param {*} options
     */
    onChooseDate(options) {
        let that = this,
            date = apply.getFullDate(options.detail)
        that.setData({
            currentSubscribeDate: date,
            currentDate: options.detail,
            showDatePopup: false
        })
    },

    /**
     * 选择行驶证
     */
    onTapLicense() {
        let that = this
        if (that.data.isAuth) {
            that.setData({
                showLicensePopup: true
            })
        } else {
            Toast.fail('请先登录')
        }
    },

    /**
     * 确认行驶证选择
     * @param {*} options
     */
    onChooseLicense(options) {
        let that = this,
            {
                value,
                index
            } = options.detail,
            driving_license_id = that.data.licenseIndex[index]
        // 新增行驶证
        if (-1 == driving_license_id) {
            wx.navigateTo({
                url: '/pages/vehicle-detail/vehicle-detail',
                success: (res) => {
                    // 通过eventChannel向被打开页面传送数据
                    res.eventChannel.emit('acceptDataFromOpenerPage', {
                        fromPage: 'order'
                    })
                }
            })
        } else {
            that.setData({
                driving_license_id: driving_license_id,
                currentLicenseNumber: value,
                showLicensePopup: false
            })
        }
    },

    /**
     * 点击优惠券
     */
    onTapCoupon() {
        Toast.fail('无可用优惠券')
        // this.setData({
        //     showCouponPopup: true
        // })
    },

    /**
     * 确认优惠券选择
     * @param {*} options
     */
    onChooseCoupon(options) {
        let that = this,
            {
                index,
                value
            } = options.detail
        coupon_id = that.data.couponIndex[index]
        that.setData({
            coupon_id: coupon_id,
            currentCouponNumber: value,
            showCouponPopup: false
        })
    },

    /**
     * 关闭弹出层
     */
    onClosePopup() {
        this.setData({
            showDatePopup: false,
            showLicensePopup: false,
            showCouponPopup: false
        })
    },

    /**
     * 提交订单
     * @param {*} options
     */
    doSubmit(options) {
        let that = this,
            errMsg = '',
            param = options.detail.value
        if (!param.driving_license_id) {
            errMsg = '请选择行驶证'
        }
        if (!param.subscribe_date) {
            errMsg = '请选择预约时间'
        }
        if (param.mobile && !/^1[3-9]\d{9}$/.test(param.mobile)) {
            errMsg = '手机号格式不正确'
        }
        if (!param.mobile) {
            errMsg = '请输入手机号'
        }
        if (errMsg) {
            Toast(errMsg)
            return false
        }
        Dialog.alert({
            title: '提示',
            message: '请于5分钟内完成支付，逾期将取消订单',
        }).then(() => {
            apply.placeOrder(param).then((res) => {
                apply.pay(res).then(() => {
                    member.getMemberData().then((result) => {
                        let userInfo = apply.getStorage('userInfo')
                        userInfo.member = result.data.member
                        apply.setStorage('userInfo', userInfo)
                    }).then(() => {
                        Toast({
                            type: 'success',
                            message: '支付成功',
                            onClose: () => {
                                wx.reLaunch({
                                    url: '/pages/order/order?status=2&page=1'
                                })
                            },
                        })
                    })
                }).catch(() => {
                    Toast({
                        type: 'fail',
                        message: '支付失败',
                        onClose: () => {
                            wx.reLaunch({
                                url: '/pages/order/order?status=0&page=1'
                            })
                        },
                    })
                })
            })
        })
    },

    /**
     * 授权后获取用户信息
     * @param {*} options
     */
    onGetUserInfo(options) {
        let that = this
        // 用户允许授权
        if (options.detail.userInfo) {
            apply.updateUserData(options.detail.userInfo).then((res) => {
                apply.setStorage('userInfo', res.data)
                that.setData({
                    isAuth: true
                })
            }).then(() => {
                Toast({
                    type: 'success',
                    message: '登录成功',
                    onClose: () => {
                        that._loadData()
                    },
                })
            })
        }
    }
})